﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.ApplicationBlocks.Data;
using System.Configuration;
using BE;
using BC;

namespace ModuleDuoc
{
    public partial class frmHD_NhapHang : ModuleDuoc.Base.frmBase
    {
        #region VAR
        string _tennhanvien = "Nguyễn Thế Sơn";
        string _maphongban = "02";
        string _type = "HDNH";
        string _source = "CSDL";
        string _flag = "add";
        string _id = "0";
        #endregion

        #region Contructor
        public frmHD_NhapHang()
        {
            InitializeComponent();
        }
        public frmHD_NhapHang(string tennhanvien, string maphongban, string type)
        {
            InitializeComponent();
            _tennhanvien = tennhanvien;
            _maphongban = maphongban;
            _type = type;
        }
        public frmHD_NhapHang(string tennhanvien, string maphongban, string type, string flag, string id)
        {
            InitializeComponent();
            _tennhanvien = tennhanvien;
            _maphongban = maphongban;
            _type = type;
            _flag = flag;
            _id = id;
        }
        #endregion

        #region FUNCTION

        /// <summary>
        /// Tính tổng tiền
        /// </summary>
        private void tinhtongtien()
        {
            float tongtien = 0;
            float tongtienCK = 0;
            for (int i = 0; i < dgvData.Rows.Count; i++)
            {
                tongtien += float.Parse(dgvData.Rows[i].Cells["gianhap"].Value.ToString()) * float.Parse(dgvData.Rows[i].Cells["soluong"].Value.ToString());
                tongtienCK += float.Parse(dgvData.Rows[i].Cells["sauvat"].Value.ToString()) * float.Parse(dgvData.Rows[i].Cells["soluong"].Value.ToString());
            }
            this.txtTongTien.Text = String.Format("{0:0}", tongtien);
            this.txtThanhTien.Text = String.Format("{0:0}", tongtienCK);
            this.txtTienCK.Text = String.Format("{0:0}", tongtien - tongtienCK);
            this.lblBangchu.Text = DICHSO.XL_DOC_SO.DOC_SO_CHUOI(double.Parse(this.txtThanhTien.Text), "đồng", "", 0);
        }

        /// <summary>
        /// Lấy số phiếu
        /// </summary>
        /// <returns></returns>
        private string getSophieu()
        {
            string sql = "select isnull(max(id),0) as [MAX] from zD_PHIEUNHAPKHO";
            DataTable dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                return _type + "-" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day + "-" + (int.Parse(dt.Rows[0]["MAX"].ToString()) + 1).ToString();
            }
            else
            {
                return _type + "-0";
            }
        }

        /// <summary>
        /// Lấy mã vạch
        /// </summary>
        /// <returns></returns>
        private int getMavach()
        {
            string sql = "select isnull(max(mavach),0)+1 as mavach from dbo.zD_PHIEUNHAPKHOCT where source <> 'old'";
            DataTable dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                return int.Parse(dt.Rows[0]["mavach"].ToString());
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// Load tên thuốc
        /// </summary>
        private void loadTenThuoc()
        {
            System.Collections.Generic.List<ZD_DM_THUOC> lstObj = new List<ZD_DM_THUOC>();
            ZD_DM_THUOCBC f = new ZD_DM_THUOCBC();
            lstObj = f.GetAll_List();
            if (lstObj.Count > 0)
            {
                this.cboTenThuoc.DataSource = lstObj;
                this.cboTenThuoc.DisplayMember = "tenvt";
                this.cboTenThuoc.ValueMember = "mavt";
            }
        }

        /// <summary>
        /// Load nhà cung cấp
        /// </summary>
        private void loadNCC()
        {
            string sql = "SELECT * from zD_NHACUNGCAP";
            DataTable dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            this.cboNhacc.DataSource = dt;
            this.cboNhacc.DisplayMember = "TENNCC";
            this.cboNhacc.ValueMember = "MANCC";
        }

        /// <summary>
        /// Load phòng ban
        /// </summary>
        private void loadPhongBan()
        {
            string sql = "SELECT * from PHONGBAN";
            DataTable dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            this.cboPhongBan.DataSource = dt;
            this.cboPhongBan.DisplayMember = "TENPHONGBAN";
            this.cboPhongBan.ValueMember = "MAPHONGBAN";
        }

        /// <summary>
        /// Load Quốc gia
        /// </summary>
        private void loadQG()
        {
            string sql = "SELECT * from QUOCGIA";
            DataTable dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            this.cboQuocGia.DataSource = dt;
            this.cboQuocGia.DisplayMember = "TENQG";
            this.cboQuocGia.ValueMember = "MAQG";
        }

        /// <summary>
        /// Load VAT
        /// </summary>
        private void loadVAT()
        {
            string sql = "SELECT * from zD_VAT";
            DataTable dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            this.cboVAT.DataSource = dt;
            this.cboVAT.DisplayMember = "VAT_NAME";
            this.cboVAT.ValueMember = "VAT";
            this.cboVAT.SelectedValue = "0";
        }

        /// <summary>
        /// Load Form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmHD_NhapHang_Load(object sender, EventArgs e)
        {
            loadInit();
            if (_flag == "add")
            {
                this.btnHuyPhieu.Enabled = false;
                this.btnInPhieu.Enabled = false;
            }
            else if (_flag == "edit")
            {
                loadData();
                this.btnInPhieu.Enabled = true;
                this.btnSave.Enabled = false;
                this.btnHuyPhieu.Enabled = true;
            }
        }

        /// <summary>
        /// Nạp dữ liệu ứng với Form edit
        /// </summary>
        private void loadData()
        {
            string sql = "SELECT * FROM view_THUOC_PHIEU_NHAPKHO where sophieu = '" + _id + "'";
            DataTable dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                this.txtSoPhieu.Text = dt.Rows[0]["sophieu"].ToString();
                this.txtNV.Text = dt.Rows[0]["manhanvien"].ToString();
                this.cboPhongBan.SelectedText = dt.Rows[0]["tenphongban"].ToString();
                this.txtSoHD.Text = dt.Rows[0]["sohd"].ToString();
                this.txtTongTien.Text = String.Format("{0:0,0}", float.Parse(dt.Rows[0]["tongtien"].ToString()));
                try
                {
                    this.txtThanhTien.Text = String.Format("{0:0,0}", float.Parse(dt.Rows[0]["tongtiensauvat"].ToString()));
                }
                catch
                {
                    this.txtThanhTien.Text = String.Format("{0:0,0}", float.Parse(dt.Rows[0]["tongtien"].ToString())); 
                }

                //Hien thi % chiet khau
                this.txtCK.Text = dt.Rows[0]["vat"].ToString();

                //Hien thi tien chiet khau
                try
                {
                    this.txtTienCK.Text = String.Format("{0:0,0}", float.Parse(dt.Rows[0]["tongtien"].ToString()) - float.Parse(dt.Rows[0]["tongtiensauvat"].ToString()));
                }
                catch {
                    this.txtTienCK.Text = "0";
                }
                this.loadDatact();
            }
        }

        /// <summary>
        /// Nạp dữ liệu chi tiết ứng với Form edit
        /// </summary>
        private void loadDatact()
        {
            string sql = "SELECT * FROM view_THUOC_PHIEUNHAPKHOCT where sophieu = '" + _id + "'";
            DataTable dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string mavt = dt.Rows[i]["mavt"].ToString();
                    string tenthhuoc = dt.Rows[i]["tenvt"].ToString();
                    string mavach = dt.Rows[i]["mavach"].ToString();
                    int soluong = int.Parse(dt.Rows[i]["soluong"].ToString());
                    string dvt = dt.Rows[i]["ten"].ToString();
                    float gianhap = float.Parse(dt.Rows[i]["dongianhap"].ToString());
                    int vat = 0;
                    try
                    {
                         vat = int.Parse(dt.Rows[i]["vat"].ToString());
                    }
                    catch { 
                    
                    }
                    float giasauvat = float.Parse(dt.Rows[i]["dongianhap"].ToString());
                    float thanhtien = float.Parse(dt.Rows[i]["thanhtien"].ToString());
                    float giaban = float.Parse(dt.Rows[i]["giaban"].ToString());
                    string solo = dt.Rows[i]["solo"].ToString();

                    dgvData.Rows.Add(mavt,
                                    tenthhuoc,
                                    mavach,
                                    soluong,
                                    dvt,
                                    gianhap,
                                    vat,
                                    giasauvat,
                                    thanhtien,
                                    giaban,
                                    solo
                                    );
                }
            }
        }

        /// <summary>
        /// Gọi các khởi tạo
        /// </summary>
        private void loadInit()
        {
            this.enableGroup(false);
            this.loadTenThuoc();
            this.loadNCC();
            this.loadPhongBan();
            this.txtNV.Text = _tennhanvien;
            this.cboPhongBan.SelectedValue = _maphongban;
            if (_type == "HDNH")
            {
                this.Text = "Hóa đơn nhập hàng";
                this.lblTitle.Text = "Hóa đơn nhập hàng";
            }
            else if (_type == "HDKK")
            {
                this.Text = "Phiếu kiểm kê đầu kỳ";
                this.lblTitle.Text = "Phiếu kiểm kê đầu kỳ";
            }
            this.cboVAT.SelectedIndex = 0;
            this.loadQG();
        }

        /// <summary>
        /// Enable các nhóm điều khiển
        /// </summary>
        /// <param name="e"></param>
        private void enableGroup(bool e)
        {
            
            this.grbDSThuoc.Enabled = e;
            this.grbHD.Enabled = e;
            this.grbThuoc.Enabled = e;
        }

        /// <summary>
        /// Thay Tab = Enter
        /// </summary>
        /// <param name="c"></param>
        /// <param name="e"></param>
        private void setTab(Control c, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                c.Focus();
            }
        }

        /// <summary>
        /// Lưu thông tin phiếu
        /// </summary>
        private void insertPhieu()
        {
            if (dgvData.Rows.Count > 0)
            {
                ZD_PHIEUNHAPKHO obj = new ZD_PHIEUNHAPKHO();
                ZD_PHIEUNHAPKHOBC bc = new ZD_PHIEUNHAPKHOBC();
                obj.Chi = false;
                obj.Ghichu = this.txtGhiChu.Text.Trim();
                obj.Huy = false;
                if (_type == "HDNH")
                {
                    obj.Loaiphieu = 1;
                }
                else if (_type == "HDKK")
                {
                    obj.Loaiphieu = 2;
                }
                obj.Machinhanh = "100";
                obj.Manhacc = this.cboNhacc.SelectedValue.ToString();
                obj.Manhanvien = this.txtNV.Text;
                try
                {
                    obj.Maphongban = this.cboPhongBan.SelectedValue.ToString();
                }
                catch
                {
                    obj.Maphongban = "";
                }
                obj.Ngaylap = DateTime.Now;
                obj.Printed = false;
                obj.Sohd = this.txtSoHD.Text;
                obj.Sophieu = this.txtSoPhieu.Text;
                obj.Tongtien = double.Parse(this.txtTongTien.Text);
                obj.Vat = double.Parse(txtCK.Text);
                if (radCHKPhanTram.Checked)
                {
                    obj.Vattype = 1;
                }
                else if (radCHKTien.Checked)
                {
                    obj.Vattype = 2;
                }
                obj.Tongtiensauvat = double.Parse(this.txtThanhTien.Text);
                bc.Insert(obj);
                insertChiTietPhieu();
                MessageBox.Show("Thêm mới phiếu nhập kho thành công!", "Thông báo");
                this.printReport();
                clear();
            }
            else
            {
                MessageBox.Show("Phiếu chưa có mặt hàng nào, vui lòng nhập mặt hàng trước khi lưu phiếu!", "Thông báo!");
            }
        }

        /// <summary>
        /// Cap nhat phieu
        /// </summary>
        private void updatePhieu()
        {
            if (dgvData.Rows.Count > 0)
            {
                ZD_PHIEUNHAPKHO obj = new ZD_PHIEUNHAPKHO();
                ZD_PHIEUNHAPKHOBC bc = new ZD_PHIEUNHAPKHOBC();
                obj.Chi = false;
                obj.Ghichu = this.txtGhiChu.Text.Trim();
                obj.Huy = false;
                if (_type == "HDNH")
                {
                    obj.Loaiphieu = 1;
                }
                else if (_type == "HDKK")
                {
                    obj.Loaiphieu = 2;
                }
                obj.Machinhanh = "100";
                obj.Manhacc = this.cboNhacc.SelectedValue.ToString();
                obj.Manhanvien = this.txtNV.Text;
                try
                {
                    obj.Maphongban = this.cboPhongBan.SelectedValue.ToString();
                }
                catch
                {
                    obj.Maphongban = "10";
                }
                obj.Ngaylap = DateTime.Now;
                obj.Printed = false;
                obj.Sohd = this.txtSoHD.Text;
                obj.Sophieu = this.txtSoPhieu.Text;
                obj.Tongtien = double.Parse(this.txtTongTien.Text);
                obj.Vat = double.Parse(txtCK.Text);
                obj.Loaiphieu = 1;
                if (radCHKPhanTram.Checked)
                {
                    obj.Vattype = 1;
                }
                else if (radCHKTien.Checked)
                {
                    obj.Vattype = 2;
                }
                obj.Tongtiensauvat = double.Parse(this.txtThanhTien.Text);

                bc.Update(obj);
                updateChiTietPhieu();
                MessageBox.Show("Cập nhật phiếu nhập kho thành công!", "Thông báo");
            }
            else
            {
                MessageBox.Show("Phiếu chưa có mặt hàng nào, vui lòng nhập mặt hàng trước khi lưu phiếu!", "Thông báo!");
            }
        }
        /// <summary>
        /// Xóa dữ liệu trên form
        /// </summary>
        private void clear()
        {
            this.txtGhiChu.Text = "";
            this.txtGiaBan.Text = "";
            this.txtGiaNhap.Text = "";
            this.txtHanSD.Text = "";
            this.txtNgaySX.Text = "";
            this.txtSL.Text = "";
            this.txtSoHD.Text = "";
            this.txtSoLo.Text = "";
            this.txtTongTien.Text = "";
        }

        /// <summary>
        /// Insert thuốc
        /// </summary>
        private void insertChiTietPhieu()
        {
            ZD_PHIEUNHAPKHOCTBC bc = new ZD_PHIEUNHAPKHOCTBC();
            if (dgvData.Rows.Count > 0)
            {
                for (int i = 0; i < dgvData.Rows.Count; i++)
                {
                    //if (checkExistMavach(dgvData.Rows[i].Cells["mavach"].Value.ToString()) == false)
                    //{
                        ZD_PHIEUNHAPKHOCT obj = new ZD_PHIEUNHAPKHOCT();
                        obj.Baogia = "";
                        obj.Dongianhap = double.Parse(dgvData.Rows[i].Cells["gianhap"].Value.ToString());
                        obj.Ghichu = "";
                        obj.Giaban = double.Parse(dgvData.Rows[i].Cells["giaban"].Value.ToString());
                        obj.Hansd = DateTime.Now;
                        obj.Hopdong = 1;
                        obj.Mavach = long.Parse(dgvData.Rows[i].Cells["mavach"].Value.ToString());
                        obj.Mavt = dgvData.Rows[i].Cells["mavt"].Value.ToString();
                        obj.Ngaysx = DateTime.Now;
                        obj.Nhacc = cboNhacc.SelectedValue.ToString();
                        obj.Sodutru = 0;
                        obj.Solo = dgvData.Rows[i].Cells["solo"].Value.ToString();
                        obj.Soluong = double.Parse(dgvData.Rows[i].Cells["soluong"].Value.ToString());
                        obj.Sophieu = this.txtSoPhieu.Text;
                        obj.Stt = 1;
                        obj.Thanhtien = double.Parse(dgvData.Rows[i].Cells["thanhtien"].Value.ToString());
                        obj.Vat = double.Parse(dgvData.Rows[i].Cells["vat"].Value.ToString());
                        bc.Insert(obj);
                    //}
                    //else
                    //{
                    //    MessageBox.Show("Mã vạch :" + dgvData.Rows[i].Cells["mavach"].Value.ToString() + " đã tồn tại!", "Thông báo");
                    //}
                }
            }
           // clearGrid();
        }

        /// <summary>
        /// Cap nhat phieu
        /// </summary>
        private void updateChiTietPhieu()
        {
            if (dgvData.Rows.Count > 0)
            {
                ZD_PHIEUNHAPKHOCTBC bc = new ZD_PHIEUNHAPKHOCTBC();
                bc.Delete(ZD_PHIEUNHAPKHOCT.ZD_PHIEUNHAPKHOCTFields.Sophieu, this.txtSoPhieu.Text);
                for (int i = 0; i < dgvData.Rows.Count; i++)
                {
                    if (checkExistMavach(dgvData.Rows[i].Cells["mavach"].Value.ToString()) == false)
                    {
                        ZD_PHIEUNHAPKHOCT obj = new ZD_PHIEUNHAPKHOCT();
                        obj.Baogia = "";
                        obj.Dongianhap = double.Parse(dgvData.Rows[i].Cells["gianhap"].Value.ToString());
                        obj.Ghichu = "";
                        obj.Giaban = double.Parse(dgvData.Rows[i].Cells["giaban"].Value.ToString());
                        obj.Hansd = DateTime.Now;
                        obj.Hopdong = 1;
                        obj.Mavach = long.Parse(dgvData.Rows[i].Cells["mavach"].Value.ToString());
                        obj.Mavt = dgvData.Rows[i].Cells["mavt"].Value.ToString();
                        obj.Ngaysx = DateTime.Now;
                        obj.Nhacc = cboNhacc.SelectedValue.ToString();
                        obj.Sodutru = 0;
                        obj.Solo = dgvData.Rows[i].Cells["solo"].Value.ToString();
                        obj.Soluong = double.Parse(dgvData.Rows[i].Cells["soluong"].Value.ToString());
                        obj.Sophieu = this.txtSoPhieu.Text;
                        obj.Stt = 1;
                        obj.Thanhtien = double.Parse(dgvData.Rows[i].Cells["thanhtien"].Value.ToString());
                        obj.Vat = double.Parse(dgvData.Rows[i].Cells["vat"].Value.ToString());
                        bc.Insert(obj);
                    }
                    else
                    {
                        MessageBox.Show("Mã vạch :" + dgvData.Rows[i].Cells["mavach"].Value.ToString() + " đã tồn tại!", "Thông báo");
                    }
                }
            }
        }
        private void clearGrid()
        {
            this.dgvData.Rows.Clear();
            this.lblBangchu.Text = "";
        }

        /// <summary>
        /// In báo cáo
        /// </summary>
        private void printReport()
        {
            string sql = "select * from view_THUOC_PHIEUNHAPKHOCT where sophieu='" + this.txtSoPhieu.Text.Trim() + "'";
            DataTable dt = new DataTable();
            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            frmShowReport frm = new frmShowReport(1);
            frmShowReport._dt = dt;
            frmShowReport._phongban = cboPhongBan.Text;
            frmShowReport._nhanvien = this.txtNV.Text;
            frmShowReport._ghichu = this.txtGhiChu.Text;
            frmShowReport._sophieu = this.txtSoPhieu.Text;
            frmShowReport._trietkhau = this.txtCK.Text;
            frmShowReport._tongtien = this.txtTongTien.Text;
            frmShowReport._thanhtien = this.lblBangchu.Text;
            frmShowReport._sohd = this.txtSoHD.Text;
            frmShowReport._nhacungcap = this.cboNhacc.Text;
            frmShowReport._vat = this.txtTienCK.Text.Trim();
            if (radCHKTien.Checked)
            {
                frmShowReport._typeTrietKhau = "VNĐ";
            }
            else
            {
                frmShowReport._typeTrietKhau = "%";
            }
            double thanhtien = 0;
            if (dgvData.Rows.Count > 0)
            {
                for (int i = 0; i < dgvData.Rows.Count; i++)
                {
                    thanhtien += double.Parse(dgvData.Rows[i].Cells["thanhtien"].Value.ToString());
                }
            }
            frmShowReport._bangchu = lblBangchu.Text;

            if (_type == "HDNH")//phieu kiem ke
            {
                frmShowReport.strC = frmShowReport.BC.PHIEUNHAPHANG;
            }
            else if (_type == "HDKK") //phieu kiem ke dau ky
            {
                frmShowReport.strC = frmShowReport.BC.PHIEUKIEMKEDAUKY;
            }
            frm.Show();
        }

        private void getDVT()
        {
            try
            {
                string sql = "select ten,mavt  from vw_DM_Thuoc where mavt='" + cboTenThuoc.SelectedValue.ToString() + "'";
                DataTable dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    this.txtDVT.Text = dt.Rows[0]["ten"].ToString();
                }
                else
                {
                }
            }
            catch (Exception ex)
            {
                this.txtDVT.Text = "E";
                this.txtDVT.ForeColor = Color.Red;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private int getMaxMavachGrid()
        {
            if (dgvData.Rows.Count > 0)
            {
                int max = int.Parse(dgvData.Rows[0].Cells["mavach"].Value.ToString());
                for (int i = 0; i < dgvData.Rows.Count; i++)
                {
                    if (max < int.Parse(dgvData.Rows[i].Cells["mavach"].Value.ToString()))
                    {
                        max = int.Parse(dgvData.Rows[i].Cells["mavach"].Value.ToString());
                    }
                }
                return max + 1;
            }
            else
            {
                return getMavach();
            }
        }

        /// <summary>
        /// Cập nhật số lượng khi trùng mã vạch
        /// </summary>
        /// <param name="mavach"></param>
        private void UpdateSL(string mavach)
        {
            if (dgvData.Rows.Count > 0)
            {
                for (int i = 0; i < dgvData.Rows.Count; i++)
                {
                    if (dgvData.Rows[i].Cells["mavach"].Value.ToString() == mavach)
                    {
                        int soluong = int.Parse(dgvData.Rows[i].Cells["soluong"].Value.ToString());
                        dgvData.Rows[i].Cells["soluong"].Value = (soluong + int.Parse(this.txtSL.Text.Trim())).ToString();
                        dgvData.Rows[i].Cells["thanhtien"].Value = int.Parse((soluong + int.Parse(this.txtSL.Text.Trim())).ToString()) * float.Parse(dgvData.Rows[i].Cells["gianhap"].Value.ToString());
                    }
                }
            }
            else
            {
            }
        }

        /// <summary>
        /// Kiểm tra chùng mã vạch
        /// </summary>
        /// <param name="mavach"></param>
        /// <returns></returns>
        private bool checkExistMavach(string mavach)
        {
            if (dgvData.Rows.Count > 0)
            {
                for (int i = 0; i < dgvData.Rows.Count; i++)
                {
                    if (dgvData.Rows[i].Cells["mavach"].Value.ToString() == mavach)
                    {
                        return true;
                    }
                }
                return false;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Tìm giá gần nhất
        /// </summary>
        private void getGiaGanNhat()
        {
            string sql = "select dongianhap,giaban,solo from zD_PHIEUNHAPKHOCT INNER JOIN zD_PHIEUNHAPKHO ON zD_PHIEUNHAPKHOCT.sophieu = zD_PHIEUNHAPKHO.sophieu  ";
            sql += " where  mavt='" + cboTenThuoc.SelectedValue.ToString() + "' order by ngaylap desc ";
            DataTable dt = new DataTable();
            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                this.txtGiaGanNhat.Text = dt.Rows[0]["dongianhap"].ToString();
                this.txtGiaBanGanNhat.Text = dt.Rows[0]["giaban"].ToString();

                this.txtGiasauVAT.Text = dt.Rows[0]["dongianhap"].ToString();
                this.txtGiaBan.Text = dt.Rows[0]["giaban"].ToString();
            }
            else
            {
            }
        }
        #endregion

        #region SET TAB
        private void txtGiaNhap_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    float giannhap = float.Parse(this.txtGiaNhap.Text.Trim());
                    try
                    {
                        this.txtGiaNhap.Text = String.Format("{0:0.00}", giannhap);
                        this.txtGiasauVAT.Text = String.Format("{0:0.00}", giannhap / int.Parse(this.txtSL.Text.Trim()));
                        setTab(txtGiasauVAT, e);
                    }
                    catch { }
                    
                }
                catch {
                    MessageBox.Show("Giá nhập không đúng!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.txtGiaNhap.Focus();
                    this.txtGiaNhap.SelectAll();
                    this.txtGiaNhap.BackColor = Color.Yellow;
                }
            }
            else
            {
                
            }
        }
        private void cboVAT_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    this.txtGiasauVAT.Text = String.Format("{0:0.00}", ((float.Parse(txtGiaNhap.Text) + ((float.Parse(txtGiaNhap.Text) * int.Parse(cboVAT.Text.ToString())) / 100))));
                    this.txtSL.Focus();
                    this.txtSL.SelectAll();
                }
                catch {
                    MessageBox.Show("VAT không đúng!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.cboVAT.Focus();
                }
            }
        }
        private void txtGiaBan_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    float giaban = float.Parse(this.txtGiaBan.Text.Trim());
                    this.txtGiaBan.Text = String.Format("{0:0,0}", giaban);
                    setTab(txtSoLo, e);
                    this.txtSoLo.SelectAll();
                }
            }
            catch {
                this.txtGiaBan.Focus();
                this.txtGiaBan.SelectAll();
            }
        }
        private void txtSL_KeyDown(object sender, KeyEventArgs e)
        {
            if (this.txtSL.Text == "")
            {
                this.txtSL.Focus();
                this.txtSL.SelectAll();
            }
            else
            {

                setTab(txtGiaNhap, e);
                this.txtMavach.SelectAll();

            }
        }
        private void txtMavach_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (this.txtMavach.Text == "")
                {
                    MessageBox.Show("Vui lòng nhập mã vạch!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.txtMavach.Focus();
                    this.txtMavach.SelectAll();
                }
                else
                {
                    if (checkExistMavach(this.txtMavach.Text.Trim()) == false)
                    {
                        setTab(txtSL, e);
                    }
                    else
                    {
                        MessageBox.Show("Mã vạch đã tồn tại!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
        }
        private void txtNgaySX_KeyDown(object sender, KeyEventArgs e)
        {
            setTab(txtHanSD, e);
        }
        private void txtHanSD_KeyDown(object sender, KeyEventArgs e)
        {
            setTab(txtGhiChu, e);
            this.txtSoLo.SelectAll();
        }
        private void txtSoLo_KeyDown(object sender, KeyEventArgs e)
        {
            setTab(txtNgaySX, e);
        }
        private void txtGhiChu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnAdd_Click(sender, e);
            }
        }
        private void cboTenThuoc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setTab(txtMavach, e);
                getDVT();
                getGiaGanNhat();
            }
        }
        
        #endregion

        #region EVENT
        private void txtMavach_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "[0123456789]") && !Char.IsControl(e.KeyChar))
                e.Handled = true;
        }
        private void txtSL_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "[0123456789]") && !Char.IsControl(e.KeyChar))
                e.Handled = true;
        }
        private bool checkExistMaVach(string mavach)
        {
            string sql = "select mavach from zD_PHIEUNHAPKHOCT where mavach='" + mavach + "'";
            DataTable dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnnectionString"], CommandType.Text, sql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                return true;
            }
            return false;
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Xác nhận xóa?", "Thông báo", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                dgvData.Rows.RemoveAt(dgvData.CurrentRow.Index);
            }
            tinhtongtien();
        }
        private void frmHD_NhapHang_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F4)
            {
                btnAdd_Click(sender, e);
            }
        }
        private void frmHD_NhapHang_KeyPress(object sender, KeyPressEventArgs e)
        {
          
        }
        private void frmHD_NhapHang_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F4)
            {
                btnAdd_Click(sender, e);
            }
        }
        private void txtGiaNhap_KeyPress(object sender, KeyPressEventArgs e)
        {
            this.txtGiaNhap.BackColor = Color.White ;
        }
        public override void btnThemMoi_Click(object sender, EventArgs e)
        {
            base.btnThemMoi_Click(sender, e);
            this.txtSoPhieu.Text = getSophieu();
            this.enableGroup(true);
            this.txtMavach.Text = getMavach().ToString();
            this.cboTenThuoc.Focus();
            clearGrid();
            clear();
            _flag = "add";
        }
        public override void btnInPhieu_Click(object sender, EventArgs e)
        {
            base.btnInPhieu_Click(sender, e);
            this.printReport();
        }
        public override void btnSave_Click(object sender, EventArgs e)
        {
            base.btnSave_Click(sender, e);
            if (_flag == "add")
            {
                this.insertPhieu();
            }
            else if (_flag == "edit")
            {
                this.updatePhieu();
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void btnExit_Click(object sender, EventArgs e)
        {
            base.btnExit_Click(sender, e);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void btnEdit_Click(object sender, EventArgs e)
        {
            base.btnEdit_Click(sender, e);
            enableGroup(true);
            this.btnSave.Enabled = true;
            
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void btnHuyPhieu_Click(object sender, EventArgs e)
        {
            base.btnHuyPhieu_Click(sender, e);
            if (MessageBox.Show("Xác nhận hủy phiếu!", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            {
                string sql = "update zD_PHIEUNHAPKHO set huy=1 where sophieu='" + this.txtSoPhieu.Text + "'";
                SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql);
                MessageBox.Show("Phiếu đã hủy", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            string mavt = this.cboTenThuoc.SelectedValue.ToString();
            string tenthhuoc = this.cboTenThuoc.Text;
            string mavach = this.txtMavach.Text.Trim();
            int soluong = int.Parse(this.txtSL.Text);
            string dvt = this.txtDVT.Text;
            float gianhap = float.Parse(this.txtGiasauVAT.Text);
            int vat = int.Parse(this.cboVAT.Text);
            float giasauvat = float.Parse(this.txtGiasauVAT.Text);
            float thanhtien = float.Parse(this.txtGiaNhap.Text);
            float giaban = float.Parse(this.txtGiaBan.Text);
            string solo = this.txtSoLo.Text;
            if (checkExistMavach(this.txtMavach.Text.Trim()) == false)
            {
                dgvData.Rows.Add(mavt,
                                tenthhuoc,
                                mavach,
                                soluong,
                                dvt,
                                gianhap,
                                vat,
                                giasauvat,
                                thanhtien,
                                giaban,
                                solo
                                );
            }
            else
            {
                UpdateSL(this.txtMavach.Text.Trim());
            }
            tinhtongtien();
            cboTenThuoc.Focus();
            _source = "GRID";
            this.txtMavach.Text = getMaxMavachGrid().ToString();
            this.txtMavach.SelectAll();
        }
        private void btnQuickAddNCC_Click(object sender, EventArgs e)
        {
            DM.DM_NHACC frm = new ModuleDuoc.DM.DM_NHACC();
            frm.ShowDialog();
            loadNCC();
        }
        #endregion  

        private void txtGiasauVAT_KeyUp(object sender, KeyEventArgs e)
        {
            
        }

        private void txtGiasauVAT_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    float giasauvat = float.Parse(this.txtGiasauVAT.Text.Trim());
                    this.txtGiaBan.Focus();
                }
            }
            catch
            {
                this.txtGiasauVAT.Focus();
                this.txtGiasauVAT.SelectAll();
            }
        }

        private void txtCK_TextChanged(object sender, EventArgs e)
        {
            
        }

        private void btnSaveQuocGia_Click(object sender, EventArgs e)
        {
            
        }

        private void radCHKTien_CheckedChanged(object sender, EventArgs e)
        {
            this.txtCK.Text = "0";
        }

        private void radCHKPhanTram_CheckedChanged(object sender, EventArgs e)
        {
            this.txtCK.Text = "0";
        }

        private void dgvData_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                dgvData.Rows[dgvData.CurrentRow.Index].Cells["thanhtien"].Value = float.Parse(dgvData.Rows[dgvData.CurrentRow.Index].Cells["sauvat"].Value.ToString()) * float.Parse(dgvData.Rows[dgvData.CurrentRow.Index].Cells["soluong"].Value.ToString());
            }
            catch { }
        }

        private void txtCK_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    this.txtCK.Text = string.Format("{0:0,0}", float.Parse(this.txtCK.Text));
                }
                catch { }
            }
        }

        private void btnHoanTac_Click(object sender, EventArgs e)
        {
            dgvData.Rows.Clear();
            loadData();
            tinhtongtien();
            this.txtTienCK.Text = "0";
            this.txtCK.Text = "0";
        }

        private void btnTinhCK_Click(object sender, EventArgs e)
        {
            if (dgvData.Rows.Count > 0)
            {
                float ck = 0;
                for (int i = 0; i < dgvData.Rows.Count; i++)
                {
                    float gianhap = float.Parse(dgvData["gianhap", i].Value.ToString());

                    if (this.txtCK.Text.Trim().Length > 0)
                    {
                        ck = float.Parse(this.txtCK.Text);
                        float dongia_vat = gianhap - (gianhap * ck) / 100;
                        dgvData.Rows[i].Cells["vat"].Value = this.txtCK.Text.Trim();
                        dgvData.Rows[i].Cells["sauvat"].Value = dongia_vat;
                        dgvData.Rows[i].Cells["thanhtien"].Value = float.Parse(dgvData.Rows[i].Cells["sauvat"].Value.ToString()) * float.Parse(dgvData.Rows[i].Cells["soluong"].Value.ToString());
                    }
                }
            }
            ///Tinh tong tien va chiet khau
            tinhtongtien();
        }

        private void dgvData_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}
